package com.cy.detectsys.controller.azure;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cy.detectsys.entity.DataCenterInfo;
import com.cy.detectsys.entity.NetPop;
import com.cy.detectsys.entity.ProbeResult;
import com.cy.detectsys.entity.vo.DataCenterInfoVo;
import com.cy.detectsys.entity.vo.ProbeResultConnectCloudVo;
import com.cy.detectsys.entity.vo.ProdeDataVo;
import com.cy.detectsys.mapper.*;
import com.cy.detectsys.model.vo.AssertStatisticVo;
import com.cy.detectsys.service.DataCenterInfoService;
import com.cy.detectsys.service.ProbeResultConnectCloudService;
import com.cy.detectsys.util.BaseResponseInfo;
import com.cy.detectsys.util.R;
import com.github.pagehelper.PageHelper;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("datacenter")
public class DataCenterController {

    @Resource
    private ProbeResultConnectCloudService probeResultConnectCloudService;

    @Resource
    private DataCenterInfoService dataCenterService;

    @Resource
    private DataCenterInfoMapper dataCenterInfoMapper;


    /**
     * 查询数据中心list
     *
     * @return
     */
    @GetMapping("list")
    public R list() {

        List<DataCenterInfo> list = dataCenterService.list();
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("totalAssetCount", list.stream().mapToInt(DataCenterInfo::getAssetCount).sum());
        resultMap.put("totalIpCount", list.stream().mapToInt(DataCenterInfo::getIpCount).sum());
        resultMap.put("data", list);
        List<Map> asset = dataCenterService.countAsset();
        resultMap.put("asset", getTopFive(asset));

        List<Map> countryDataCenterSort = dataCenterInfoMapper.getCountryDataCenterSort();
        resultMap.put("countryDataCenterSort", countryDataCenterSort);

        List<Map> dataCenterAssetSort = dataCenterInfoMapper.getDataCenterAssetSort();
        resultMap.put("dataCenterAssetSort", dataCenterAssetSort);


        //应用层

//        微软云已识别云服务总数量
        Integer cloudServiceCount = dataCenterInfoMapper.getCloudServiceCount();
        resultMap.put("cloudServiceCount", cloudServiceCount);

//        微软云数据中心 的 云服务、云组件数量统计排名
        ArrayList<AssertStatisticVo> dataCenterCloudServerSort = new ArrayList<>();
        ArrayList<AssertStatisticVo> dataCenterComponentServerSort = new ArrayList<>();

        for (DataCenterInfo dataCenterInfo : list) {
            try {
            String cloudServerSort = dataCenterInfo.getCloudServerSort();
            List<AssertStatisticVo> assertStatisticVos = JSON.parseArray(cloudServerSort, AssertStatisticVo.class);
            int sum = assertStatisticVos.stream().mapToInt(AssertStatisticVo::getCount).sum();
            AssertStatisticVo assertStatisticVo = new AssertStatisticVo();
            assertStatisticVo.setCount(sum);
            assertStatisticVo.setField(dataCenterInfo.getAvailableAreas());
            dataCenterCloudServerSort.add(assertStatisticVo);


                String cloudConponentSort = dataCenterInfo.getCloudConponentSort();
                List<AssertStatisticVo> cloudConponentSortVos = JSON.parseArray(cloudConponentSort, AssertStatisticVo.class);
                int sum2 = cloudConponentSortVos.stream().mapToInt(AssertStatisticVo::getCount).sum();
                AssertStatisticVo assertStatisticVo2 = new AssertStatisticVo();
                assertStatisticVo2.setCount(sum2);
                assertStatisticVo2.setField(dataCenterInfo.getAvailableAreas());
                dataCenterComponentServerSort.add(assertStatisticVo2);
            } catch (Exception e) {
                System.out.println(e);
            }


        }

        List<AssertStatisticVo> datacenterCloudServerSort = getOrderedList(dataCenterCloudServerSort);
        List<AssertStatisticVo> datacenterCloudComponentSort = getOrderedList(dataCenterComponentServerSort);
        resultMap.put("datacenterCloudServerSort", datacenterCloudServerSort);
        resultMap.put("datacenterCloudComponentSort", datacenterCloudComponentSort);

//        resultMap.put("cloudComponent", JSON.parseArray(s));


        return R.ok(resultMap);
    }

    private List<AssertStatisticVo> getOrderedList(ArrayList<AssertStatisticVo> assertStatisticVos) {

        List<AssertStatisticVo> orderedList = assertStatisticVos.stream().sorted(new Comparator<AssertStatisticVo>() {
            @Override
            public int compare(AssertStatisticVo o1, AssertStatisticVo o2) {
                return o1.getCount() > o2.getCount() ? -1 : o1.getCount() == o2.getCount() ? 0 : 1;
            }
        }).collect(Collectors.toList());


        if (orderedList.size() > 5) {
            return orderedList.subList(0, 5);
        }
        return orderedList;
    }


    @Resource
    private NetPopMapper netPopMapper;
    @Resource
    private CableInfoMapper cableInfoMapper;


    /**
     * 物理层： pop数量、海底光缆数量
     */
    @GetMapping("physics")
    public R physics() {

        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("popCount", netPopMapper.selectCount(null));
        resultMap.put("cableCount", cableInfoMapper.selectCount(null));
        return R.ok(resultMap);
    }


    @Resource
    private AsTopoMapper asTopoMapper;

    /**
     * 网络层： 拓扑路径数量、资产统计排名
     */
    @GetMapping("net")
    public R net() {

        HashMap<String, Object> resultMap = new HashMap<>();
        List<Map> assetlink = dataCenterInfoMapper.getAssetlink();
        resultMap.put("assetlink", assetlink);
        resultMap.put("topo", asTopoMapper.selectCount(null));
        resultMap.put("assetCount", asTopoMapper.selectCount(null));
        return R.ok(resultMap);
    }


    /**
     * 应用层：
     */
    @GetMapping("app")
    public R app() {
        HashMap<String, Object> resultMap = new HashMap<>();
        List<Map> assetlink = dataCenterInfoMapper.getAssetlink();
        resultMap.put("assetlink", assetlink);
        resultMap.put("topo", asTopoMapper.selectCount(null));

        String s = new String("[{\"count\":67418,\"field\":\"\"},{\"count\":7382,\"field\":\"AzureWebPubSub\"},{\"count\":7254,\"field\":\"AzureAppService\"},{\"count\":136,\"field\":\"AzureStorage\"},{\"count\":130,\"field\":\"AzureEventHub\"}]");

        resultMap.put("cloudService", JSON.parseArray(s));
        resultMap.put("cloudComponent", JSON.parseArray(s));

        return R.ok(resultMap);
    }

    public <T> List<T> getTopFive(List<T> orginList) {
        if (orginList.size() > 5) {
            return orginList.subList(0, 5);
        }
        return orginList;
    }

//

    /**
     * 根据数据中心查找资产数量和独立ip数量 再次点击详情
     */
    @RequestMapping("queryFullInfo")
    public R queryFullInfo(@RequestParam String centerName) {

        return probeResultConnectCloudService.queryFullInfo(centerName);

    }

    @GetMapping("queryCloudInfo")
    public R queryCloudInfo(@RequestParam String centerName) {
        return probeResultConnectCloudService.queryCloudInfo(centerName);
    }


    @Resource
    private ProbeResultConnectCloudMapper probeResultConnectCloudMapper;
    @Resource
    private ProbeResultMapper probeResultMapper;


    @GetMapping("updateff")
    public R updateff() {
        List<DataCenterInfo> dataCenterInfos = dataCenterInfoMapper.selectList(null);
        for (DataCenterInfo dataCenterInfo : dataCenterInfos) {

            try {
                String dataCenterName = dataCenterInfo.getDataCenterName();
                List<AssertStatisticVo> cloudServiceList = probeResultConnectCloudMapper.groupByCloudServiceByDataCenterName(dataCenterName);
                HashMap<String, Integer> cloudComponentMap = new HashMap<>();
                HashMap<String, Integer> webFrameMap = new HashMap<>();
                HashMap<String, Integer> webAppMap = new HashMap<>();
                List<String> ipList = probeResultConnectCloudMapper.queryIndependenceIp(dataCenterName);
                QueryWrapper<ProbeResult> probeResultQueryWrapper = new QueryWrapper<>();
                probeResultQueryWrapper.ne("match_results", "null");
                probeResultQueryWrapper.in("ip", ipList);

                List<ProbeResult> assets = probeResultMapper.selectList(probeResultQueryWrapper);
                for (ProbeResult asset : assets) {
                    String matchResults = asset.getMatchResults();
                    try {
                        List<Map> productList = JSON.parseArray(matchResults, Map.class);
                        for (Map map : productList) {
                            String product = (String) map.get("Product");
                            cloudComponentMap.put(product, cloudComponentMap.getOrDefault(product, 0) + 1);
                            String subtype = (String) map.get("Subtype");
                            if ("Web框架".equals(subtype)) {
                                webFrameMap.put(product, webFrameMap.getOrDefault(product, 0) + 1);
                            }
                            String type = (String) map.get("Type");
                            if ("服务应用".equals(type)) {
                                webAppMap.put(product, webAppMap.getOrDefault(product, 0) + 1);
                            }
                        }
                    } catch (Exception e) {
                        System.out.println();
                    }

                }


                dataCenterInfo.setCloudConponentSort(JSON.toJSONString(getOrderedList(cloudComponentMap)));
                dataCenterInfo.setWebFrameSort(JSON.toJSONString(getOrderedList(webFrameMap)));
                dataCenterInfo.setWebAppSort(JSON.toJSONString(getOrderedList(webAppMap)));
                dataCenterInfo.setCloudServerSort(JSON.toJSONString(cloudServiceList));

                UpdateWrapper<DataCenterInfo> objectUpdateWrapper = new UpdateWrapper<>();
                objectUpdateWrapper.eq("data_center_name", dataCenterName);
                dataCenterInfoMapper.update(dataCenterInfo, objectUpdateWrapper);


            } catch (Exception e) {
                System.out.println();
            }
        }


        return R.ok();
    }


    // 根据字段值的出现次数进行排序
    public List<AssertStatisticVo> getOrderedList(HashMap<String, Integer> assetsMap) {
        ArrayList<AssertStatisticVo> assertStatisticVos = new ArrayList<>();
        for (String port : assetsMap.keySet()) {
            AssertStatisticVo assertStatisticVo = new AssertStatisticVo();
            assertStatisticVo.setCount(assetsMap.get(port));
            assertStatisticVo.setField(port);
            assertStatisticVos.add(assertStatisticVo);
        }

        List<AssertStatisticVo> orderedList = assertStatisticVos.stream().sorted(new Comparator<AssertStatisticVo>() {
            @Override
            public int compare(AssertStatisticVo o1, AssertStatisticVo o2) {
                return o1.getCount() > o2.getCount() ? -1 : o1.getCount() == o2.getCount() ? 0 : 1;
            }
        }).collect(Collectors.toList());


        if (orderedList.size() > 5) {
            return orderedList.subList(0, 5);
        }
        return orderedList;
    }

    public static void main(String[] args) {

        HashMap<String, String> map = new HashMap<>();
        map.put("cloudService", "20.140.65.44");
        map.put("serviceCount", "33");
        ArrayList<Object> objects = new ArrayList<>();
        objects.add(map);
        System.out.println(JSON.toJSONString(objects));

    }


    /**
     *  数据中心 ip规模统计
     */

    @GetMapping("updatefff")
    public void updatefff() {
        List<DataCenterInfo> dataCenterInfos = dataCenterInfoMapper.selectList(null);
        for (DataCenterInfo dataCenterInfo : dataCenterInfos) {
        //   [{"ipv4":231},{"ipv6":33}]
            String dataCenterName = dataCenterInfo.getDataCenterName();
            HashMap<String, Integer> count1 = new HashMap<>();
            //计算ipv4网段数量
            Integer ipv4count = dataCenterInfoMapper.selectIpv4count(dataCenterName);

            count1.put("ipv4", ipv4count);
            //计算ipv4网段数量
//            Integer ipv6count = dataCenterInfoMapper.selectIpv6count(dataCenterName);
            Integer ipv6count = 0;
            HashMap<String, Integer> count2 = new HashMap<>();

            count2.put("ipv6", ipv6count);


            List<Object> objects = new ArrayList<>();
            objects.add(count1);
            objects.add(count2);
            dataCenterInfo.setIpScale(JSON.toJSONString(objects));
            dataCenterInfoMapper.updateById(dataCenterInfo);
        }

    }


    /**
     * @description:
     * @param:  数据中心列表
     * @return:
     * @author asus
     * @date: 2024/6/17 13:44
     */

    @PostMapping("/getDataCenterList")
    private BaseResponseInfo getDataCenterList(@RequestBody (required = false) DataCenterInfoVo dataCenterInfoVo) {
        return dataCenterService.getDataCenterList(dataCenterInfoVo);
    }


    /**
     * @description:  数据中心国家下拉框
     * @param:
     * @return:
     * @author asus
     * @date: 2024/6/7 11:06
     */
    @PostMapping("/getDataCenterXContryBox")
    private BaseResponseInfo getDataCenterXContryBox() {
        return dataCenterService.getDataCenterXContryBox();
    }

    /**
     * @description: TODO
     * @author  数据中心区域下拉框
     * @date 2024/6/7 16:40
     * @version 1.0
     */
    @PostMapping("/getDataCenterXAvailableAreasBox")
    private BaseResponseInfo getDataCenterXAvailableAreasBox() {
        return dataCenterService.getDataCenterXAvailableAreasBox();
    }

    /**
     * @description: TODO
     * @author 数据中心ip列表
     * @date 2024/5/31 11:10
     * @version 1.0
     */
    @PostMapping("/getDataCenterIpList")
    private BaseResponseInfo getDataCenterIpList( @RequestBody(required = false) ProbeResultConnectCloudVo probeResultConnectCloudVo) {
        return dataCenterService.getDataCenterIpList(probeResultConnectCloudVo);
    }

    /**
     * @description: TODO
     * @author 数据中心ip列表中数据中心的下拉框
     * @date 2024/6/7 10:39
     * @version 1.0
     */
    @PostMapping("/getDataCenterIpListBox")
    private BaseResponseInfo getDataCenterIpListBox() {
        return dataCenterService.getDataCenterIpListBox();
    }



    /**
     * @description: TODO
     * @author  数据中心資產端口下拉框
     * @date 2024/6/7 16:40
     * @version 1.0
     */
    @PostMapping("/getDataCenterXPortBox")
    private BaseResponseInfo getDataCenterXPortBox() {
        return dataCenterService.getDataCenterXPortBox();
    }

    /**
     * @description: TODO
     * @author 资产探测数据列表
     * @date 2024/5/31 15:49
     * @version 1.0
     */
    @PostMapping("/assetProbeDataList")
    private BaseResponseInfo assetProbeDataList(@RequestBody(required = false) ProdeDataVo prodeDataVo) {
        return dataCenterService.assetProbeDataList(prodeDataVo);
    }





}
